import {Component} from '@angular/core';
import {IonicPage, NavParams} from 'ionic-angular';
import {MapProvider} from "@providers/map";
import {WorkerProvider} from '@providers/interface/worker';
import {DialogProvider} from "@providers/dialog";

declare let AMap;

@IonicPage()
@Component({
  selector: 'map-display-order-page',
  templateUrl: 'map-display-order.html',
})
export class MapDisplayOrderPage {

  map: any;//地图对象
  datas: any[] = this.navParams.data;
  mapIsComplete: boolean = false;

  constructor(public navParams: NavParams,
              private mapService: MapProvider,
              private worker: WorkerProvider,
              private dialog: DialogProvider,) {
  }

  ionViewWillEnter() {
    this.loadMap();

  }

  loadMap() {

    this.mapService.createMap(document.getElementById("container")).then(map => {
      this.mapIsComplete = true;
      this.map = map;
      this.getGeoLocation(this.map);
      //this.loadUserLocationUI();
      this.createMarkers();
      //this.addMarkerToMap();
      this.map.setFitView();
    }, err => {
      console.log(err);
    })

  }

  /**
   * 定位当前位置
   * @param map
   */
  getGeoLocation(map) {
    AMap.plugin('AMap.Geolocation', function() {
      let geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：5s
        buttonPosition:'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function(status,result){
        if(status=='complete'){
          onComplete(result)
        }else{
          onError(result)
        }
      });
    });
    //解析定位结果
    function onComplete(data) {
      console.log('定位结果：' + data.position);
      console.log('定位类别：' + data.location_type);
      if(data.accuracy){
        console.log('精度：' + data.accuracy + ' 米');
      }//如为IP精确定位结果则没有精度信息
      console.log('是否经过偏移：' + (data.isConverted ? '是' : '否'));
    }
    //解析定位错误信息
    function onError(data) {
      console.log("定位失败");
      console.log("失败原因排查信息:" + data.message);
    }
  }

  /**
   * 标记遍历添加点击事件
   */
  addClick(marker, data) {
    marker.on('click', () => {
      this.addInfoWindow(data);
    });
  }

  /**添加客户坐标和绑定坐标点击事件
   *
   *传入值为json{map: this.map,
   *                  icon: markers.icon,
   *                  position: [markers.position[0], markers.position[1]],
   *            }
   *
   */
  createMarkers() {
    //测试代码
    for (let i = 0; i < this.datas.length; i++) {
      let data = this.datas[i];

      // 创建一个 Marker 实例：
      let address = data['ADDRESS'];
      let url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&key=23e99e94aec6ac8d7cf9fb0fbbc13fd3";

      this.worker.geocode(url).then(v => {
        let loa: string = v['geocodes'][0]['location'];
        console.log("loa:" + loa);
        let lng = loa.split(",")[0];
        let lat = loa.split(",")[1];
        let marker = new AMap.Marker({
          position: [lng, lat],   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        });
        data['lng'] = lng;
        data['lat'] = lat;
        //添加标记
        this.addClick(marker, data);
        marker.setMap(this.map);
      }).catch(e => {
        this.dialog.showAlert("提示: 网络或地址错误");
      });
    }
  }

  /**
   * 添加信息窗体
   */
  addInfoWindow(data) {
    //在指定位置打开信息窗体
    //构建信息窗体中显示的内容
    let info = [];
    let content = `
                <div class="w08 font_size_large font_weight_bold">
                            <i class="fa fa-map-marker mr5" style="color:#347eff;"></i>${data.ADDRESS}
                        </div>
                        <span class="w04 mt5 fr tr">${data.ID}</span>
                        <span class="w08 mt5">${data.NAME} / ${data.MOBILE}</span>
                        <span class="w08 mt5 font_red">备注:${data.BZ ? data.BZ : '无'}</span>
                        <span class="w04 mt5 fr tr font_red">${data.THRUTIME}  ${data.YYSJD}</span>
            `;
    info.push(content);
    let infoWindow = new AMap.InfoWindow({
      content: info.join("")  //使用默认信息窗体框样式，显示信息内容
    });

    infoWindow.open(this.map, [data['lng'], data['lat']]);
  }

}
